﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Strom.Core.Accounts;
using Strom.Core.Characters;

namespace Strom.Core.Network.Packets
{
    public class CharactersListPacket : IPacket
    {
        public static byte ID = 3;

        public Graphic.ILoginForm LoginForm { get; set; }

        public CharactersListPacket(Graphic.ILoginForm loginForm = null)
        {
            LoginForm = loginForm;
        }

        public void Unpack(BaseClient client, Packet packet)
        {
            byte count = packet.Reader.ReadByte();
            var charaters = new List<Character>();

            for(byte i = 0; i < count; i++)
            {
                short lenght = packet.Reader.ReadInt16();
                byte[] datas = packet.Reader.ReadBytes(lenght);
                charaters.Add(Character.Deserialize(datas));
            }

            LoginForm.ConnectSuccess(client, charaters);
        }

        /// <summary>
        /// Envoyer la liste des persos d'un compte
        /// </summary>
        /// <param name="client">client actuel</param>
        /// <param name="datas">[0] current account(Account)</param>
        public void Pack(BaseClient client, params object[] datas)
        {
            var currentAccount = (Account) (datas[0]);
            var pw = new PacketWriter();

            lock (currentAccount.Characters)
            {
                pw.Write((byte)currentAccount.Characters.Count);
                foreach (var current in currentAccount.Characters)
                {
                    pw.Write(current.Serialize());
                }
            }

            client.Send(pw.CompilePacket(ID));
        }
    }
}
